-- UIStrengthenDetail
-- Create by zouyb
-- 炼金强化详细界面

--UIStrengthenDetail继承自Layer
UIStrengthenDetail = class("UIStrengthenDetail", function()
    return cc.Layer:create();
end);

function UIStrengthenDetail.create(info)
    return UIStrengthenDetail.new(info);
end

-- 构造函数
function UIStrengthenDetail:ctor(info)
    self:setName("UIStrengthenDetail");
    self.info = info;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/workshop/StrengthenDetail.csb");
    self:addChild(node);
    self.node = node;

    -- 注册点击事件
    self:registerTouchEvent();

    self.costParentNode = findChildByName(self.node, "CT/cost");
    self.originCostParentPosX = self.costParentNode:getPositionX();
    self.originCostParentPosY = self.costParentNode:getPositionY();

    -- 重绘
    self:redraw();

    self:registerEventCallback();

    -- 适配
    self:resize();
end

function UIStrengthenDetail:registerEventCallback()
    -- 可能会直接购买碎片
    EventMgr.register("UIStrengthenDetail", event.DIRECT_BUY_GOODS, function(args)
        -- 提示购买的数量
        alertBuyGoodsTip(args.bonus);
        self:redraw(true);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIStrengthenDetail");
        elseif ev == "enter" then

        end
    end);
end

-- 注册点击事件
function UIStrengthenDetail:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIStrengthenDetail");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册强化按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/strengthen");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local id = self.info.id;
            local ret, requireAmount = AlchemyWorkshopM.canStrengthen(id);
            if ret ~= true then
                if type(ret) == "string" then
                    if ret == "not_enough_gem_to_strengthen" then
                        -- 钻石不足
                        showGemLackConfirm();
                        return;
                    elseif ret == "not_enough_money_to_strengthen" then
                        -- 金币不足
                        showMoneyLackConfirm(requireAmount);
                        return;
                    end

                    alert(getLocStr(ret));
                end
                return;
            end

            local gemCost = self:calcStrengthenGemCost(id);

            -- 强化炼金项后续处理
            local function addEffect()
                -- 本地先加
                self.info.level = self.info.level + 1;
                if self.info.times ~= nil then
                    self.info.times = self.info.times + 1;
                end

                local uiForm = UIMgr.getCurrentScene():getFormByName("UIWorkshopStrengthen");
                if uiForm then
                    uiForm:playStrengthenEffect(id);
                end

                -- 处理召唤页面提示
                self:handleSummonTabHint();

                -- 关闭界面
                UIMgr.getCurrentScene():removeFormByName("UIStrengthenDetail");
            end

            if gemCost > 0 then
                -- 如果需要花费钻石，则弹出确认提示框
                local level = AlchemyWorkshopM.getStrengthenLevel(id);
                local msg = string.format(getLocStr("strengthen_confirm"), gemCost, level + 1);
                local title = AlchemyWorkshopM.query(id, "name");

                local function callback()
                    Operation.cmd_strengthen_workshop_item(id);
                    -- 后续处理
                    addEffect();
                end

                local function cancelCallBack()
                    -- 关闭界面
                    UIMgr.getCurrentScene():removeFormByName("UIStrengthenDetail");
                end

                confirm2(CONFIRM_TYPE_OK, title, msg, callback,
                    cancelCallBack, getLocStr("btn_text_intensify"));
            else
                Operation.cmd_strengthen_workshop_item(id);
                -- 后续处理
                addEffect();
            end
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
end

-- 处理召唤页面提示
function UIStrengthenDetail:handleSummonTabHint()
    local msg;
    if self.info.id == 7 and self.info.level == 5 then
        -- 暗钢满足时触发
        msg = getLocStr("puppet_research_hint");
    elseif self.info.id == 8 and self.info.level == 5  then
        -- 魂晶满级时触发
        msg = getLocStr("mystery_research_hint");
    else
        return;
    end

    local function callback()
        local uiForm = UIMgr.getCurrentScene():getFormByName("UIWorkshopStrengthen");
        if uiForm then
            UIMgr.getCurrentScene():removeForm(uiForm);
        end

        confirm2(CONFIRM_TYPE_OK, getLocStr("slime_note"), msg);
    end
    performWithDelay(UIMgr.getCurrentScene(), callback, 1);
end

-- 界面重绘
function UIStrengthenDetail:redraw(notAjust)
    local level = self.info.level or 0;
    local id = self.info.id;

    local maxTimes = AlchemyWorkshopM.query(id, "max_strengthen_times");
    local initMaxTimes = maxTimes;
    local times = self.info.times or 0;

    -- 如果配置了公式，那么调用公式计算最大次数
    local prefix = "formula_";
    if type(maxTimes) == "string" and
        string.startWith(maxTimes, "formula_") then
        local formulaName = string.sub(maxTimes, string.len(prefix) + 1);
        maxTimes = FormulaM.invoke(formulaName, false);
        initMaxTimes = FormulaM.invoke(formulaName, true);
    end

    -- 强化按钮
    local btnBuy = findChildByName(self.node, "CT/strengthen");
    local levelStr;
    local titleStr = getLocStr("btn_text_strengthen");
    if id == 2 then
        titleStr = getLocStr("btn_text_recruit");
    end

    if times >= initMaxTimes then
        levelStr = getLocStr("level_max");
        btnBuy:setTitleText(titleStr .. " " .. levelStr);
    else
        levelStr = getLevelStr(level + 1);
        btnBuy:setTitleText(titleStr .. " " .. levelStr);
    end

    if times >= maxTimes then
        setButtonEnabled(btnBuy, false);
    else
        setButtonEnabled(btnBuy, true);
    end

    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(AlchemyWorkshopM.query(id, "name"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 道具描述1
    local desc1Label = findChildByName(self.node, "CT/desc1");
    local desc = AlchemyWorkshopM.getStrengthenDesc(id, level);

    -- 野外生存工具需要特殊取值
    if id == 19 then
        local searchTime = { 5, 20, 60, 120, 240, 480, 720};
        if searchTime[level + 1] < 60 then
            desc = string.gsub(desc, "{0}", tostring(searchTime[level + 2] - searchTime[level + 1]));
            desc = string.gsub(desc, "{1}", getLocStr("minute"));
            desc = string.gsub(desc, "{2}", tostring(searchTime[level + 1]));
        else
            desc = string.gsub(desc, "{0}", string.format("%0.1f", (searchTime[level + 2] - searchTime[level + 1]) / 60));
            desc = string.gsub(desc, "{1}", getLocStr("hour"));
            desc = string.gsub(desc, "{2}", string.format("%0.1f", searchTime[level + 1] / 60));
        end
    end

    local addValue = AlchemyWorkshopM.query(id, "add_value");
    local initValue = AlchemyWorkshopM.query(id, "init_value");
    if initValue > 0 then
        desc = string.gsub(desc, "{0}", tostring(initValue + level * addValue));
    else
        desc = self:getDesc(desc, id, level);
    end

    TextStyleM.setTextStyle(desc1Label,TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(desc1Label, desc);

    -- 图标
    local item = findChildByName(self.node, "CT/item");
    local icon = item:getChildByName("icon");
    local fileName = AlchemyWorkshopM.query(id, "icon")
    if AlchemyWorkshopM.query(id, "path") == "pet" then
        icon:loadTexture(getHeroIconPath(fileName));
    else
        icon:loadTexture(getWorkshopStrengthenIconPath(fileName));
    end
    local scale = AlchemyWorkshopM.query(id, "scale");
    if type(scale) == "number" and scale > 0 then
        icon:setScale(scale / 100);
    end

    local frame = item:getChildByName("frame");
    fileName = AlchemyWorkshopM.query(id, "bg");
    frame:loadTexture(getWorkshopStrengthenIconPath("bg"..fileName));

    -- 是否可强化
    local canStrengthen = AlchemyWorkshopM.canStrengthen(id);

    -- 等级
    local levelLabel = item:getChildByName("level");
    if times >= initMaxTimes then
        levelLabel:setString(getLocStr("level_max"));
    else
        levelLabel:setString(getLevelStr(level));
    end

    local color;
    if canStrengthen ~= true then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    else
        color = TextStyleM.TEXT_COLOR_BRIGHT_YELLOW;
    end

    TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL, color, true);
    levelLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

    if level == 0 then
        frame:setOpacity(96);
        icon:setOpacity(128);
        levelLabel:setVisible(false);
    end

    -- 花费
    self:initCost();

    if not notAjust then
        -- 调整高度
        self:adjustHeight();
    end
end

-- 获取强化项对应的描述
function UIStrengthenDetail:getDesc(desc, id, level)
    local maxTimes = AlchemyWorkshopM.query(id, "max_strengthen_times");
    local times = self.info.times or 0;

    -- 如果配置了公式，那么调用公式计算最大次数
    local prefix = "formula_";
    if type(maxTimes) == "string" and
        string.startWith(maxTimes, "formula_") then
        local formulaName = string.sub(maxTimes, string.len(prefix) + 1);
        maxTimes = FormulaM.invoke(formulaName, true);
    end

    if id == 2 or id == 3 then
        -- 工匠招募 或 冷却装置
        local interval = FormulaM.invoke("GET_ALCHEMY_PRODUCE_INTERVAL", ME.user);
        desc = string.gsub(desc, "{0}", tostring(interval));
    elseif id == 4 then
        -- 工匠雕像
        -- 最大累计时间
        local offlineLimit = AlchemyWorkshopM.calcMaxOffline();

        -- 将秒转换为小时
        offlineLimit    = string.format("%0.1f", offlineLimit/3600) ;
        desc = string.gsub(desc, "{0}", tostring(offlineLimit));
    elseif id == 13 then
        -- 傀儡研究
        local arr = FormulaM.invoke("CALC_PUPPET_SLIME_SCRAP_NUM", ME.user, level);

        desc = string.gsub(desc, "{0}", tostring(arr[3]));

    elseif id == 14 then
        -- 神秘研究
        local arr = FormulaM.invoke("CALC_HELLFIRE_SLIME_SCRAP_NUM", ME.user, level);

        desc = string.gsub(desc, "{0}", tostring(arr[3]));

    elseif id == 22 then
        -- 傀儡研究II
        local arr = FormulaM.invoke("CALC_TITAN_SLIME_SCRAP_NUM", ME.user, level);

        desc = string.gsub(desc, "{0}", tostring(arr[3]));

    elseif id == 23 then
        -- 神秘研究II
        local arr = FormulaM.invoke("CALC_SAINT_DRAGON_SLIME_SCRAP_NUM", ME.user, level);

        desc = string.gsub(desc, "{0}", tostring(arr[3]));
    end

    return desc;
end

-- 花费金币
function UIStrengthenDetail:initCost()
    local costLabel = findChildByName(self.node, "CT/cost");
    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false);
    costLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_SIZE_SMALL + 5);

    local id = self.info.id;
    local level = AlchemyWorkshopM.getStrengthenLevel(id);
    local cost = AlchemyWorkshopM.getStrengthenCost(id, level + 1);

    local index = 0;
    local costStr = "";
    for _, arr in pairs(cost) do
        index = index + 1;

        local name, nameStr;
        local needNum = arr[3];
        local curNum;

        local function changeColor(current, need, str)
            -- 满足时显示蓝色，不足时显示红色
            if current < need then
                str = string.gsub(str, "{0}", "red");
            else
                str = string.gsub(str, "{0}", "blue");
            end

            return str;
        end

        local amountStr;
        if arr[1] == 1 then
            name = ItemM.query(arr[2], "name");
            nameStr = string.format(getLocStr("need_item_amount"), name, needNum);
            curNum = ItemM.getAmount(ME.user, arr[2]);

            -- 材料
            amountStr = string.format(getLocStr("current_amount"), curNum);
        elseif arr[1] == 2 then
            name = FieldsM.getFieldName(arr[2]);
            nameStr = string.format(getLocStr("need_money_amount"), name, needNum);
            curNum = ME.user:queryAttrib(arr[2]);

            -- 金币/钻石
            amountStr = "";
        end

        amountStr = changeColor(curNum, needNum, amountStr);
        nameStr = changeColor(curNum, needNum, nameStr);
        costStr = costStr .. nameStr .. " " .. amountStr .. "\n";
    end

    -- 已升级到最大
    local maxTimes = AlchemyWorkshopM.query(id, "max_strengthen_times");
    local times = self.info.times or 0;
    local initMaxTimes = maxTimes;

    -- 如果配置了公式，那么调用公式计算最大次数
    local prefix = "formula_";
    local chapterId = 0;
    if type(maxTimes) == "string" and
        string.startWith(maxTimes, "formula_") then
        local formulaName = string.sub(maxTimes, string.len(prefix) + 1);

        maxTimes, chapterId = FormulaM.invoke(formulaName, false);
        chapterId = chapterId + 1;
        initMaxTimes = FormulaM.invoke(formulaName, true);
    end

    if times >= maxTimes then
        if initMaxTimes > maxTimes then
            costStr = string.format(getLocStr("hint_chapter_limit"), DungeonAreaM.query(chapterId, "name"));
        else
            costStr = getLocStr("hint_reach_max_level");
        end
    end

    applyString(costLabel, costStr);
end

-- 计算强化的钻石消耗
function UIStrengthenDetail:calcStrengthenGemCost(id)
    local level = AlchemyWorkshopM.getStrengthenLevel(id);
    local cost = AlchemyWorkshopM.getStrengthenCost(id, level + 1);

    for _, arr in pairs(cost) do
        if arr[1] == 2 and arr[2] == "gem" then
            return arr[3];
        end
    end

    return 0;
end

-- 调整高度
function UIStrengthenDetail:adjustHeight()
    local costLabel = findChildByName(self.node, "CT/cost");
    local lineNum = costLabel:getVirtualRenderer():getStringNumLines();

    local delta = (3 - lineNum) * TextStyleM.TEXT_SIZE_SMALL;
    if delta == 0 then
        return;
    end

    costLabel:setPositionY(costLabel:getPositionY() + delta / 2);

    local btnBuy = findChildByName(self.node, "CT/strengthen");
    btnBuy:setPositionY(btnBuy:getPositionY() + delta);

    local bg = findChildByName(self.node, "CT/template/bg");

    local bgDelta = delta / bg:getScaleY();
    local bg3 = findChildByName(self.node, "CT/template/bg/bg3");
    bg3:setPositionY(bg3:getPositionY() + bgDelta );
    local bg4 = findChildByName(self.node, "CT/template/bg/bg4");
    bg4:setPositionY(bg4:getPositionY() + bgDelta);
end

-- 适配
function UIStrengthenDetail:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


